<template>
  <div class="container" style="background: #EEEEEE7F; min-height: 100vh;">
    <!-- 顶部导航 -->
    <van-nav-bar
        title="选择房间"
        left-text="返回"
        left-arrow
        @click-left="router.back()"
    />

    <!-- 搜索框 -->
    <van-search v-model="searchValue" placeholder="请输入房间号" />

    <!-- 楼层+房间选择 -->
    <van-tree-select
        v-model:active-id="activeRoomId"
        v-model:main-active-index="activeFloorIndex"
        :items="treeItems"
        @click-item="handleRoomSelection"
        style="flex-grow: 1;"
    >
      <!-- 右侧内容插槽，自定义图片+房间列表 -->
      <template #content>
        <div class="content-header">
          <van-image
              :src="floorImages[activeFloorIndex]"
              @click="showImagePreview = true"
              width="100%"
              fit="cover"
          />
        </div>

        <!-- 房间列表，双列 -->
        <div class="content-list">
          <div
              v-for="item in treeItems[activeFloorIndex]?.children || []"
              :key="item.id"
              class="content-list-item"
              @click="handleRoomSelection(item)"
          >
            {{ item.text }}
          </div>
        </div>
      </template>
    </van-tree-select>
  </div>
  <van-image-preview v-model:show="showImagePreview" :images="[floorImages[activeFloorIndex]]" />
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { toPage } from '@/apps/client/utils/routerUtil'

import apple1 from '@/assets/floor/floor-1.jpg'
import apple2 from '@/assets/floor/floor-2.jpg'
import apple3 from '@/assets/floor/floor-3.jpg'
import apple4 from '@/assets/floor/floor-4.jpg'
import apple5 from '@/assets/floor/floor-5.jpg'
import apple6 from '@/assets/floor/floor-6.jpg'

const showImagePreview = ref(false);
const floorImages: string[] = [apple1, apple2, apple3, apple4, apple5, apple6]
console.log(floorImages)

const router = useRouter()

// 搜索关键字
const searchValue = ref('')

// 当前选中房间id和楼层索引
const activeRoomId = ref(null)
const activeFloorIndex = ref(0)

// 楼层及房间数据
const selectedRoomType = sessionStorage.getItem('selectRoomType')
const floors: any[] = JSON.parse(sessionStorage.getItem('floors') || '[]')
const floorRoomGroupMap = JSON.parse(sessionStorage.getItem('groupRoomsByFloor') || '{}')


// 构建树形数据（楼层+符合类型的房间）
function buildTreeItems() {
  const items = []

  floors.forEach(floor => {
    const childrenRooms = []

    if (floorRoomGroupMap[floor.id]) {
      floorRoomGroupMap[floor.id].forEach(room => {
        if (selectedRoomType === room.type) {
          childrenRooms.push({
            text: `${room.number} ${room.subType}`,
            id: room.id,
            number: room.number,
          })
        }
      })
    }

    if (childrenRooms.length) {
      items.push({ text: floor.name, children: childrenRooms })
    }
  })

  return items
}

// 初始化数据
const originalTreeItems = buildTreeItems()
const treeItems = ref([...originalTreeItems])

// 监听搜索关键字，过滤房间
watch(searchValue, (keyword: string) => {
  const kw = keyword.trim()
  if (!kw) {
    treeItems.value = [...originalTreeItems]
    return
  }

  treeItems.value = originalTreeItems
      .map(floor => {
        const filteredRooms = floor.children.filter(room => room.number.toString().includes(kw))
        return filteredRooms.length ? { ...floor, children: filteredRooms } : null
      })
      .filter(Boolean)
})

// 点击房间处理函数
function handleRoomSelection(item) {
  // 记录选择的房间
  sessionStorage.setItem('selectRoom', JSON.stringify(item))

  // 判断跳转路由或返回
  const targetRoute = sessionStorage.getItem('selectRoomRouteName')
  if (targetRoute === 'back') {
    router.back()
  } else {
    toPage(targetRoute)
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

/* 保持楼层导航文字不换行 */
::v-deep(.van-tree-select__nav-item) {
  white-space: nowrap;
}

/* 图片容器底部间距 */
.content-header {
  margin: 8px 8px 0 8px;
}

/* 右侧房间列表双列 */
.content-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 8px;
}

.content-list-item {
  width: 48%;
  padding: 10px;
  background-color: white;
  border-radius: 4px;
  text-align: center;
  box-sizing: border-box;
  border: 1px solid #ddd;
  cursor: pointer;
  user-select: none;
  transition: background-color 0.3s;
}

.content-list-item:hover {
  background-color: #f5f5f5;
}

/* 默认楼层字体颜色 浅蓝色 */
::v-deep(.van-tree-select__nav-item) {
  color: #6ca0f6; /* 浅蓝色 */
}

/* 选中楼层字体颜色 深蓝色 */
::v-deep(.van-tree-select__nav-item.van-tree-select__nav-item--active) {
  color: #0047ab; /* 深蓝色 */
  font-weight: 600; /* 可选，加粗更明显 */
}


</style>
